package org.csu.mypetstore.web.servlets;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;


public class AddProductToCartServlet extends HttpServlet{
    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";

    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
        doGet(req,res);
    }

    protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
        HttpSession httpSession = request.getSession();
        String itemId = request.getParameter("itemId");
        String listPrice = request.getParameter("listPrice");
        double price = Double.parseDouble(listPrice);
        Account account = (Account) httpSession.getAttribute("account");
        Cart  cart = (Cart) httpSession.getAttribute("cart");
        //CatalogService catalogService = new CatalogService();
        cart.incrementQuantityByItemId(itemId);
        httpSession.setAttribute("cart.subTotal",cart.getSubTotal());
        //String total  = (String) httpSession.getAttribute("cart."+itemId+".total");
        double total = cart.getQuantityByItemId(itemId) * price;
        httpSession.setAttribute("cart",cart);
        httpSession.setAttribute("cart.total",total);
        if(account != null)
        {
            CatalogService.insertCart(account,itemId);
        }
    }

}
